defmodule PhoenixApi.ApiParamController do
  use PhoenixApi.Web, :controller

  @doc "/api/param/:name"
  def rest_param1(conn, %{"name" => name}) do
    json conn, %{
      "result": "success from rest_param1",
      "message": "your name is " <> name,
    }
  end

  @doc "/api/param/:name/:age"
  def rest_param2(conn, %{"name" => name, "age" => age}) do
    json conn, %{
      "result": "success from rest_param2",
      "message": "your name is " <> name <> " and age is " <> age,
    }
  end

  @doc "/api/param?name=xxx&age=yyy"
  def get_param(conn, params) do
    if Map.has_key?(params, "age") do
      json conn, %{
        "result": "success from get_param",
        "message": "your name is " <> params["name"] <> " and age is " <> params["age"],
      }
    else
      json conn, %{
        "result": "success from get_param",
        "message": "your name is " <> params["name"],
      }
    end
  end

  @doc "/api/param"
  def post_param(conn, params) do
    if Map.has_key?(params, "age") do
      json conn, %{
        "result": "success from post_param",
        "message": "your name is " <> params["name"] <> " and age is " <> params["age"],
      }
    else
      json conn, %{
        "result": "success from post_param",
        "message": "your name is " <> params["name"],
      }
    end
  end

  @doc "/api/json-param"
  def json_param(conn, params) do
    if Map.has_key?(params, "age") do
      json conn, %{
        "result": "success from json_param",
        "message": "your name is " <> params["name"] <> " and age is " <> to_string(params["age"]),
      }
    else
      json conn, %{
        "result": "success from json_param",
        "message": "your name is " <> params["name"],
      }
    end
  end

  @doc "/api/file-param"
  def file_param(conn, params) do
    filepath = "/tmp/downloadfile.txt"
    if Map.has_key?(params, "age") do
      File.write(filepath, "your name is " <> params["name"] <> " and age is " <> to_string(params["age"]))
    else
      File.write(filepath, "your name is " <> params["name"])
    end

    conn |> send_file(200, filepath)
  end

  @doc "/api/file-param"
  def upload_param(conn, params) do

    file = params["file"]
    File.cp(file.path, "/tmp/upload.file")

    json conn, %{
      "result": "success from file_param",
      "message": "your name is " <> params["name"] <> " and age is " <> to_string(params["age"])
      <> " and the filename which you upload is " <> file.filename,
    }
  end
end
